package com.paas.form.controller;


import com.alibaba.fastjson.JSON;
import com.bpm.feign.model.ProcessCmd;
import com.bpm.feign.service.IBpmProcessInstanceService;
import com.paas.common.model.BaseUserInfo;
import com.paas.common.model.RestResponse;
import com.paas.common.util.StringUtil;
import com.paas.common.web.SystemConst;
import com.paas.form.entity.*;
import com.paas.form.service.*;
import com.paas.form.vo.DataChangeVo;
import com.paas.form.vo.SysValueVo;
import com.paas.form.vo.ValidateResultVo;
import com.paas.plus.tool.codeRule.server.ICodeRuleServer;
import com.paas.plus.tool.codec.server.ICodecServer;
import com.paas.plus.tool.form.model.DataChange;
import com.paas.plus.tool.form.model.DataChangeInfo;
import com.paas.plus.tool.form.model.DataChangeInfoDetail;
import com.paas.plus.tool.form.server.FormServer;
import com.paas.plus.tool.validate.model.CheckResponse;
import com.paas.plus.tool.validate.server.ValidateServer;
import com.publics.entity.UcUserEntity;
import com.publics.feign.service.IUcUserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.paas.common.util.BeanUtil;
import com.paas.common.web.annotion.OperLog;
import com.paas.common.web.controller.BaseController;
import com.paas.common.web.oper.OprLogConstant;


import javax.xml.crypto.Data;

@RestController
@RequestMapping(value = "/form/dataChangeInfo")
@Api(description = "视图模块", tags = "")
public class FormDataChangeInfoController extends BaseController {

    @Autowired
    public IFormDataChangeInfoService dataChangeInfoService;

    @Autowired
    public IFormDataChangeInfoDetailService dataChangeInfoDetailService;

    @Autowired
    public FormServer formServer;

    @Autowired
    public IBpmProcessInstanceService bpmProcessInstanceService;

    @Autowired
    public IFormAttributeService attributeService;

    //定版属性
    @Autowired
    public IFormAttributePubService formAttributePubService;

    @Autowired
    public ValidateServer validateServer;

    @Autowired
    public IUcUserService ucUserService;

    @Autowired
    public ICodeRuleServer codeRuleServer;

    @Autowired
    public IFormViewPubService formViewPubService;



    @RequestMapping(value = "/save", method = RequestMethod.POST)
    @ApiOperation(value = "保存信息", notes = "保存信息")
    @OperLog(operType = OprLogConstant.ADD, operModul = "", operDescribe = "-保存")
    public void save(@RequestBody FormDataChangeInfoEntity formDataChangeInfoEntity) throws ParseException {
        if (BeanUtil.isNotEmpty(formDataChangeInfoEntity)) {
            injectUpdateDataAuth(formDataChangeInfoEntity);
        }
        dataChangeInfoService.save(formDataChangeInfoEntity);
    }

    @RequestMapping(value = "/getCodeValue", method = RequestMethod.POST)
    @ApiOperation(value = "获取编码值", notes = "获取编码值")
    public RestResponse getCodeValue(@RequestBody HashMap<String,Object> codeQuery) throws Exception {
        if(BeanUtil.isNotEmpty(codeQuery)){
            HashMap<String,Object> maps= (HashMap<String, Object>) codeQuery.get("map");
            RestResponse codeValue=codeRuleServer.generatedCode(codeQuery.get("parentCode").toString(),codeQuery.get("id").toString(),maps);
            return codeValue;

        }

        return RestResponse.error("获取编码参数为空");

    }


    @RequestMapping(value = "/dataCheck", method = RequestMethod.POST)
    @ApiOperation(value = "修改数据校验", notes = "修改数据校验")
    public List<ValidateResultVo> dataCheck(@RequestBody DataChangeVo<ProcessCmd> dataChangeVo) throws Exception {

        return dataCheckFunction(dataChangeVo);

    }


    public List<ValidateResultVo> dataCheckFunction(DataChangeVo<ProcessCmd> dataChangeVo) throws Exception {

        List<FormDataChangeInfoDetailEntity> dataDetails = dataChangeVo.getDataChangeInfoDetails();

        //校验失败结果集合
        List<ValidateResultVo> resultList = new ArrayList<>();


        if (dataDetails.size() > 0) {
            //修改记录根据ViewId分组
            Map<String, List<FormDataChangeInfoDetailEntity>> dataDetailMap = dataDetails.stream().collect(Collectors.groupingBy(FormDataChangeInfoDetailEntity::getViewId));
            for (String viewId : dataDetailMap.keySet()) {
                //根据viewId查出对应视图的所有属性
                FormAttributePubEntity attrBean = new FormAttributePubEntity();
                attrBean.setViewId(viewId);
                attrBean.setStatus(SystemConst.NORMAL_STATUS);
                List<FormAttributePubEntity> formAttrList = formAttributePubService.getList(attrBean);
                if (formAttrList.size() > 0) {
                    //key属性名,value 校验规则id组成的Map
                    Map<String, FormAttributePubEntity> regularMap = formAttrList.stream().collect(Collectors.toMap(item ->{
                        return item.getCode().toUpperCase();
                    }, item -> item));

                    List<FormDataChangeInfoDetailEntity> items = dataDetailMap.get(viewId);
                    //遍历变更项进行校验
                    for (FormDataChangeInfoDetailEntity item : items) {
                        if (StringUtil.isNotEmpty(item.getAttributeName()) && StringUtil.isNotEmpty(item.getUpdateValue())) {
                            if(StringUtil.isNotEmpty(regularMap.get(item.getAttributeName()).getRegularRule())){
                                String regularRuleId = regularMap.get(item.getAttributeName().toUpperCase()).getRegularRule();

                                CheckResponse checkResult = validateServer.check(regularRuleId, item.getUpdateValue());
                                //如果校验不通过则记录失败
                                if (!checkResult.isSuccess()) {
                                    ValidateResultVo valResult = new ValidateResultVo();
                                    valResult.setViewId(viewId);
                                    valResult.setPrimaryKeyValue(item.getPrimaryKeyValue());
                                    valResult.setRegularRuleId(regularRuleId);
                                    valResult.setCheckField(item.getAttributeName());
                                    valResult.setCheckValue(item.getUpdateValue());
                                    valResult.setCheckResult(false);
                                    valResult.setCheckMsg(checkResult.getErrorMsg());

                                    valResult.setCheckFieldName(regularMap.get(item.getAttributeName().toUpperCase()).getName());

                                    resultList.add(valResult);
                                }

                            }



                        }


                    }


                }


            }


        }

        return resultList;


    }


    /*
     * 先校验再保存，校验不通过，则返回校验信息，校验成功进行保存
     * */
    @RequestMapping(value = "/saveDataChange", method = RequestMethod.POST)
    @ApiOperation(value = "保存修改数据", notes = "保存修改数据")
    @OperLog(operType = OprLogConstant.ADD, operModul = "", operDescribe = "-保存修改数据")
    public List<ValidateResultVo> saveDataChange(@RequestBody DataChangeVo<ProcessCmd> dataChangeVo) throws Exception {
        if (BeanUtil.isNotEmpty(dataChangeVo.getFormDataChangeInfoEntity())) {
            //先进行校验
            List<ValidateResultVo> validateResultVos = dataCheckFunction(dataChangeVo);
            if (validateResultVos.size() > 0) {
                return validateResultVos;
            }


            BaseUserInfo baseUserInfo = getUserInfo();
            FormDataChangeInfoEntity formDataChangeInfoEntity = dataChangeVo.getFormDataChangeInfoEntity();
            injectUpdateDataAuth(formDataChangeInfoEntity);
            formDataChangeInfoEntity.setStatus(SystemConst.NORMAL_STATUS);
            dataChangeInfoService.save(formDataChangeInfoEntity);

            //保存明细
            List<FormDataChangeInfoDetailEntity> dataChangeInfoDetails = dataChangeVo.getDataChangeInfoDetails();
            if (dataChangeInfoDetails.size() > 0) {
                for (FormDataChangeInfoDetailEntity changeDetail : dataChangeInfoDetails) {
                    changeDetail.setStatus(SystemConst.NORMAL_STATUS);
                    changeDetail.setChangeInfoId(formDataChangeInfoEntity.getId());
                }
                dataChangeInfoDetailService.saveBatch(dataChangeInfoDetails);
            }

            //如果不需要跑审批流程，则进行表数据修改

            if ("2".equals(dataChangeVo.getNeedApproval())) {  //1:需要流程，2不需要流程
                DataChange dataChange = new DataChange();
                dataChange.setViewId(formDataChangeInfoEntity.getViewDataId());
                dataChange.setDataChangeInfoId(formDataChangeInfoEntity.getId());
                Boolean changeResult = dataChangeInfoService.viewDataChange(dataChange);

            } else {
                ProcessCmd processCmd = dataChangeVo.getProcessCmd();

                if (BeanUtil.isNotEmpty(processCmd)) {
                    processCmd.setBusinessKey(formDataChangeInfoEntity.getId());
                    processCmd.setData(JSON.toJSONString(formDataChangeInfoEntity));
                    processCmd.setAppId(baseUserInfo.getAppId());
                    if(StringUtil.isNotEmpty(processCmd.getTaskId())){
                        bpmProcessInstanceService.completeSubmitTask(processCmd);
                    }else {
                        bpmProcessInstanceService.startProcessInstance(processCmd);
                    }

                }
            }


        }

        return null;

    }


    @RequestMapping(value = "/getSysValue", method = RequestMethod.GET)
    @ApiOperation(value = "获取系统值", notes = "获取系统值")
    public SysValueVo getSysValue(String sysValueName) throws Exception {

        if (StringUtil.isNotEmpty(sysValueName)) {
            SysValueVo sysValueVo=new SysValueVo();

            BaseUserInfo baseUserInfo = getUserInfo();
            if(sysValueName.equals("sysTime")){
                Date day=new Date();
                SimpleDateFormat df=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                sysValueVo.setValue(df.format(day));
                sysValueVo.setName(df.format(day));

            }else if(sysValueName.equals("sysUser")){
                sysValueVo.setValue(baseUserInfo.getUserId());
                sysValueVo.setName(baseUserInfo.getUserName());

            }
            return sysValueVo;

        }
        return null;


    }


    @RequestMapping(value = "/getUserName", method = RequestMethod.GET)
    @ApiOperation(value = "获取用户名", notes = "获取用户名")
    public SysValueVo getUserName(String userId) throws Exception {

        if (StringUtil.isNotEmpty(userId)) {
            SysValueVo sysValueVo=new SysValueVo();
            UcUserEntity bean=ucUserService.queryById(userId);
            if(BeanUtil.isNotEmpty(bean)){
                sysValueVo.setName(bean.getUserName());
                sysValueVo.setValue(bean.getId());
                return sysValueVo;
            }

        }
        return null;


    }





    @RequestMapping(value = "/agreeApproval", method = RequestMethod.POST)
    @ApiOperation(value = "同意申请", notes = "同意申请")
    public RestResponse agreeApproval(String bussinessKey) throws Exception {
        if (StringUtil.isNotEmpty(bussinessKey)) {
            System.out.println("变更主表id为：" + bussinessKey + "的审批被同意");

            FormDataChangeInfoEntity formDataChangeInfoEntity = dataChangeInfoService.getById(bussinessKey);
            if (BeanUtil.isNotEmpty(formDataChangeInfoEntity)) {
                formDataChangeInfoEntity.setApprovalStatus("1");
                dataChangeInfoService.save(formDataChangeInfoEntity);

                DataChange dataChange = new DataChange();
                dataChange.setViewId(formDataChangeInfoEntity.getViewDataId());
                dataChange.setDataChangeInfoId(formDataChangeInfoEntity.getId());
                Boolean changeResult = dataChangeInfoService.viewDataChange(dataChange);
                return RestResponse.success();
            }

        }
        return RestResponse.error();

    }

    @RequestMapping(value = "/refuseApproval", method = RequestMethod.POST)
    @ApiOperation(value = "驳回申请", notes = "驳回申请")
    public RestResponse refuseApproval(String bussinessKey) {
        if (StringUtil.isNotEmpty(bussinessKey)) {
            System.out.println("变更主表id为：" + bussinessKey + "的审批被驳回");
            FormDataChangeInfoEntity formDataChangeInfoEntity = dataChangeInfoService.getById(bussinessKey);
            if (BeanUtil.isNotEmpty(formDataChangeInfoEntity)) {
                formDataChangeInfoEntity.setApprovalStatus("3");
                dataChangeInfoService.save(formDataChangeInfoEntity);

            }

        }
        return RestResponse.error();
    }

    @RequestMapping(value = "/disApproval", method = RequestMethod.POST)
    @ApiOperation(value = "反对申请", notes = "反对申请")
    public RestResponse disApproval(String bussinessKey) {
        if (StringUtil.isNotEmpty(bussinessKey)) {

            FormDataChangeInfoEntity formDataChangeInfoEntity = dataChangeInfoService.getById(bussinessKey);
            if (BeanUtil.isNotEmpty(formDataChangeInfoEntity)) {
                formDataChangeInfoEntity.setApprovalStatus("2");
                dataChangeInfoService.save(formDataChangeInfoEntity);

            }

        }
        return RestResponse.error();
    }


    @RequestMapping(value = "/saveBatch", method = RequestMethod.POST)
    @ApiOperation(value = "批量保存信息", notes = "批量保存信息")
    @OperLog(operType = OprLogConstant.UPDATE, operModul = "", operDescribe = "-批量保存修改")
    public void saveBatch(@RequestBody List<FormDataChangeInfoEntity> list) throws ParseException {
        if (list != null && list.size() > 0) {
            injectUpdateDataAuth(list);
        }
        dataChangeInfoService.saveBatch(list);
    }

    @RequestMapping(value = "/delectById", method = RequestMethod.GET)
    @ApiOperation(value = "根据Id删除数据", notes = "根据Id删除数据")
    @OperLog(operType = OprLogConstant.DELETE, operModul = "", operDescribe = "-删除")
    public void delectById(String id) {
        if (null != id && !"".equals(id)) {
            FormDataChangeInfoEntity formDataChangeInfoEntity = new FormDataChangeInfoEntity();
            injectUpdateDataAuth(formDataChangeInfoEntity);
            formDataChangeInfoEntity.setId(id);
            dataChangeInfoService.deleteByEntity(formDataChangeInfoEntity);
        }
    }

    @RequestMapping(value = "/deleteBatchByIds", method = RequestMethod.POST)
    @ApiOperation(value = "根据Id批量删除数据", notes = "根据Id批量删除数据")
    @OperLog(operType = OprLogConstant.DELETE, operModul = "", operDescribe = "-批量删除")
    public void deleteBatchByIds(@RequestBody List<String> ids) {
        if (null != ids && ids.size() > 0) {
            FormDataChangeInfoEntity formDataChangeInfoEntity = new FormDataChangeInfoEntity();
            injectUpdateDataAuth(formDataChangeInfoEntity);
            //dataChangeInfoService.deleteBatchIds(ids);
            dataChangeInfoService.deleteBatchIdsWithPermission(ids, formDataChangeInfoEntity);
        }
    }

    @RequestMapping(value = "/queryById", method = RequestMethod.GET)
    @ApiOperation(value = "根据Id查询对象", notes = "根据Id查询对象")
    public FormDataChangeInfoEntity queryById(String id) {
        FormDataChangeInfoEntity bean = dataChangeInfoService.getById(id);
        return bean;
    }


    @RequestMapping(value = "/queryDetailMapById", method = RequestMethod.GET)
    @ApiOperation(value = "根据Id查询对象", notes = "根据Id查询对象")
    public Map<String, List<FormDataChangeInfoDetailEntity>> queryDetailMapById(String id) {
        Map<String, List<FormDataChangeInfoDetailEntity>> detailMap = new HashMap<String, List<FormDataChangeInfoDetailEntity>>();

        FormDataChangeInfoDetailEntity bean = new FormDataChangeInfoDetailEntity();
        bean.setChangeInfoId(id);
        List<FormDataChangeInfoDetailEntity> detailList = dataChangeInfoDetailService.getList(bean);
        if (detailList.size() > 0) {

            Map<String, List<FormDataChangeInfoDetailEntity>> detailMapbyViewId = new HashMap<String, List<FormDataChangeInfoDetailEntity>>();
            detailMapbyViewId = detailList.stream().collect(Collectors.groupingBy(FormDataChangeInfoDetailEntity::getViewId));
            for(String key : detailMapbyViewId.keySet()){
                FormViewPubEntity viewBean = formViewPubService.getById(key);

                FormAttributePubEntity  attributePubEntity=new FormAttributePubEntity();
                attributePubEntity.setViewId(key);
                List<FormAttributePubEntity> list = formAttributePubService.getList(attributePubEntity);

                if(BeanUtil.isNotEmpty(viewBean)){
                    for (int i = 0; i <detailList.size() ; i++) {
                        if(detailList.get(i).getViewId().equals(key)){
                            detailList.get(i).setViewName(viewBean.getName());
                            if(list.size()>0){
                                for (int j = 0; j <list.size() ; j++) {
                                    if(list.get(j).getCode().equals(detailList.get(i).getAttributeName())||list.get(j).getCode().toUpperCase().equals(detailList.get(i).getAttributeName())){
                                        detailList.get(i).setName(list.get(j).getName());
                                    }

                                }
                            }


                        }
                    }

                }

            }

            detailMap = detailList.stream().collect(Collectors.groupingBy(FormDataChangeInfoDetailEntity::getLinkTable));



        }
        return detailMap;
    }


    @RequestMapping(value = "/queryBatchByIds", method = RequestMethod.POST)
    @ApiOperation(value = "根据Id查询对象列表", notes = "根据Id查询对象列表")
    public List<FormDataChangeInfoEntity> queryBatchByIds(@RequestBody List<String> ids) {
        List<FormDataChangeInfoEntity> list = dataChangeInfoService.getBatchByIds(ids);
        return list;
    }

    @RequestMapping(value = "/queryPage", method = RequestMethod.GET)
    @ApiOperation(value = "模板分页查询", notes = "模板分页查询")
    public IPage<FormDataChangeInfoEntity> queryPage(FormDataChangeInfoEntity formDataChangeInfoEntity, Integer currentPage, Integer pageSize) {
        if (currentPage == null) {
            currentPage = 1;
        }
        if (pageSize == null) {
            pageSize = 10;
        }
        injectCheckDataAuth(formDataChangeInfoEntity);
        IPage<FormDataChangeInfoEntity> pageBean = dataChangeInfoService.getPage(formDataChangeInfoEntity, currentPage, pageSize);
        return pageBean;
    }

    @RequestMapping(value = "/queryList", method = RequestMethod.GET)
    @ApiOperation(value = "模板查询", notes = "模板查询")
    public List<FormDataChangeInfoEntity> queryList(FormDataChangeInfoEntity formDataChangeInfoEntity) {
        injectCheckDataAuth(formDataChangeInfoEntity);
        List<FormDataChangeInfoEntity> list = dataChangeInfoService.getList(formDataChangeInfoEntity);
        return list;
    }
}